package com.njlime.cms.controller.sys;

import com.njlime.cms.entities.Information;
import com.njlime.cms.sdk.weibo4j.Oauth;
import com.njlime.cms.sdk.weibo4j.Timeline;
import com.njlime.cms.sdk.weibo4j.Users;
import com.njlime.cms.sdk.weibo4j.http.AccessToken;
import com.njlime.cms.sdk.weibo4j.http.ImageItem;
import com.njlime.cms.sdk.weibo4j.model.Status;
import com.njlime.cms.sdk.weibo4j.model.User;
import com.njlime.cms.sdk.weibo4j.model.WeiboException;
import com.njlime.cms.sdk.weibo4j.util.URLEncodeUtils;
import com.njlime.cms.sdk.weibo4j.util.WeiboConfig;
import com.njlime.cms.service.sys.InformationService;
import com.njlime.cms.util.UrlUtil;
import com.njlime.core.base.controller.BaseController;
import com.njlime.core.exception.ExceptionState;
import com.njlime.core.utils.StringUtil;
import com.njlime.sys.entities.UnitWxConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 微博发布
 * Created by Dean on 2017/10/14.
 */
@Controller
public class WeiBoController extends BaseController {
    private static final String weiboCode = "weiboCode";
    private static final String weiboToken = "weiboToken";
    private static final String weiboUser = "weiboUser";
    @Resource
    private InformationService informationService;

    @RequestMapping(value = "/weiboCallBack")
    public ModelAndView weiboCallBack(String code, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView loginSuccess = new ModelAndView("/sys/content/information/loginSuccess");
        loginSuccess.addObject("type","weibo");
        try {
            System.out.println("code: " + code);
            request.getSession().setAttribute(weiboCode, code);
            Oauth oauth = new Oauth();
            try {
                AccessToken token = oauth.getAccessTokenByCode(code);
                request.getSession().setAttribute(weiboToken, token);
                Users um = new Users(token.getAccessToken());
                User user = um.showUserById(token.getUid());
                request.getSession().setAttribute(weiboUser, user);
            } catch (WeiboException e) {
                if (401 == e.getStatusCode()) {
                    System.out.println("Unable to get the access token.");
                } else {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            loginSuccess.setViewName("/sys/content/information/loginFail");
            return loginSuccess;
        }
        return loginSuccess;
    }


    @RequestMapping(value = "/getWeiBoCode")
    @ResponseBody
    public String getWeiBoCode(HttpServletRequest request, HttpServletResponse response) {
        Object code = request.getAttribute("weiboCode");
        if (code == null || code.toString().equals("")) {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION,"获取微博信息失败");
        }
        return toJsonSuccessData(code);
    }

    @RequestMapping(value = "/cancelWeiboCallBack")
    @ResponseBody
    public String cancelWeiboCallBack() {
        System.out.println("cancelWeiboCallBack");
        return "cancelWeiboCallBack";
    }

    /**
     * 发送微博
     *
     * @param statuses
     * @param request
     * @return
     */
    @RequestMapping(value = "weibo/updateStatus")
    @ResponseBody
    public String updateStatus(String statuses, HttpServletRequest request) {
        try {
            AccessToken token = (AccessToken) request.getSession().getAttribute(weiboToken);
            String access_token = token.getAccessToken();
            Timeline tm = new Timeline(access_token);
            System.out.print("token");
            Status status = tm.updateStatus(statuses);
            System.out.println("status" + status);
            return toJsonSuccessData();
        } catch (WeiboException e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, e.getMessage());
        } catch (Exception e) {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "未知错误");
        }
    }

    @RequestMapping(value = "weibo/getToken")
    @ResponseBody
    public String updateStatus(HttpServletRequest request) {
        AccessToken token = (AccessToken) request.getSession().getAttribute(weiboToken);
        return toJsonSuccessData(token);
    }

    @RequestMapping(value = "weibo/informationSTWB")
    @ResponseBody
    public String informationSTWB(int id, HttpServletRequest request) {
        Information information = informationService.findOne(id);
        try {
            byte[] buffer = UrlUtil.getImageFromNetByUrl(information.getTheme_img1());
            ImageItem imageItem = new ImageItem(buffer);
            AccessToken token = (AccessToken) request.getSession().getAttribute(weiboToken);
            String access_token = token.getAccessToken();
            Timeline tm = new Timeline(access_token);
            String content = "";
            if(!StringUtil.isEmpty(information.getSource_url())){
                content = information.getTitle() + " " + information.getSource_url();  //微博正文内容
            }else{
                String baseUrl = request.getScheme() + "://" + request.getServerName() + request.getContextPath() + "/";
                content = information.getTitle() + " " + baseUrl + "/app/page?pv=info_detail&unit_id=" + information.getUnit_id();  //微博正文内容
            }
            content = URLEncodeUtils.encodeURL(content);
            Status status = tm.uploadStatusShare(content, imageItem);
            System.out.println("status" + status);
            return toJsonSuccessData();
        } catch (WeiboException e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "未知错误");
        }

    }

    @RequestMapping(value = "weibo/getWeiboUser")
    @ResponseBody
    public String getWeiboUser(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute(weiboUser);
        if (user == null) {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION,"查询用户失败");
        }
        return toJsonSuccessData(user);
    }


    /**
     * 变文件为字节
     *
     * @param file
     * @return
     */
    public static byte[] getBytesFromFile(File file) {
        long length = file.length();
        byte[] bytes = new byte[(int) length];
        try {
            InputStream is = new FileInputStream(file);
            // Read in the bytes
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length
                    && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }
            // Ensure all the bytes have been read in
            if (offset < bytes.length) {
                throw new IOException("Could not completely read file " + file.getName());
            }
            // Close the input stream and return bytes
            is.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return bytes;
    }

    @RequestMapping(value = "weibo/weiboCheck")
    @ResponseBody
    public String ttCheck(HttpServletRequest request, HttpServletResponse response) {
        Map<String,Object> result = new HashMap<>();
        result.put("key", WeiboConfig.getValue("client_ID"));
        result.put("uri", WeiboConfig.getValue("redirect_URI"));
        return toJsonSuccessData(result);
    }

}
